<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html>
  <head>
    <title>ocamljs 0.1 - interface</title>
  </head>
  <body>

<h3>Interfacing with Javascript</h3>

<p>You can call Javascript functions in the same way you call C
primitives in ordinary OCaml, by declaring them 'external'. Put the
external functions in a file foo.js, and add foo.js to the link
line. The names of the primitives are read out of the Javascript file;
any name after 'var' or 'function' at the beginning of the line is
included.</p>

<p>You can also use special 'external' declarations to avoid having to
write trivial wrapper functions for Javascript field accesses and
method calls. The following special prefixes to the function name are
recognized:</p>

<table>
  <tr><td><b>prefix</b></td><td><b>compiles to</b></td></tr>
  <tr><td>#</td><td>method call</td></tr>
  <tr><td>.</td><td>read slot</td></tr>
  <tr><td>=</td><td>assign slot</td></tr>
  <tr><td>@</td><td>function call for builtin function, not checked against primitives</td></tr>
</table>

<p>The object-related prefixes expect the object as the first
argument. For example, if you declare <code>external foo : bar -> unit
= "#foo"</code> and call <code>foo b</code>, that compiles
to <code>b.foo()</code>.</p>

<p>Finally, there are several special 'external' symbols which produce
Javascript syntax when compiled. They can also help you to avoid
trivial wrappers in some cases. They expect particular
OCaml <em>syntax</em> as arguments.

<table>
  <tr><td><b>symbol</b></td><td><b>expects args</b></td><td><b>compiles to</b></td></tr>
  <tr><td>$assign</td><td>[lvalue; expression]</td><td>lvalue = expression</td></tr>
  <tr><td>$call</td><td>function::args</td><td>function(args)</td></tr>
  <tr><td>$false</td><td>unused</td><td>false</td></tr>
  <tr><td>$fieldref</td><td>[expression; id] (id as string)</td><td>expression.id</td></tr>
  <tr><td>$function</td><td>[function]</td><td>underlying Javascript function</td></tr>
  <tr><td>$hashref</td><td>[expression1; expression2]</td><td>expression1[expression2]</td></tr>
  <tr><td>$new</td><td>id::args (id as string)</td><td>new id(args)</td></tr>
  <tr><td>$new id</td><td>args</td><td>new id(args)</td></tr>
  <tr><td>$null</td><td>unused</td><td>null</td></tr>
  <tr><td>$obj</td><td>alist of ids and expressions</td><td>object literal</td></tr>
  <tr><td>$this</td><td>unused</td><td>this</td></tr>
  <tr><td>$throw</td><td>expression</td><td>throw expression</td></tr>
  <tr><td>$true</td><td>unused</td><td>true</td></tr>
  <tr><td>$var</td><td>id (as string)</td><td>id</td></tr>
</table>

<p>The '$new id' symbol uses the native name argument to external,
e.g. <code>external "$new" "Foo" : unit -> foo</code>. See the Mozilla
library for examples of the use of these declarations. See comp_ccall
in src/ocamljs/jsgen.ml to see exactly what they do.<p>

</body>
</html>
